//
//  DetailViewController.m
//  PgyHelper
//
//  Created by CleverPeng on 2020/8/13.
//  Copyright © 2020 CleverPeng. All rights reserved.
//

#import "DetailViewController.h"
#import "RequestTool.h"
#import "PPTools.h"
#import "MoreVersionsVC.h"
#import "UIImage+Ex.h"

@interface DetailViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *aooIconIMV;
@property (weak, nonatomic) IBOutlet UILabel *appNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *installButton;
@property (weak, nonatomic) IBOutlet UITextField *appkeyTF;
@property (weak, nonatomic) IBOutlet UIButton *clearInfoButton;

@property (weak, nonatomic) IBOutlet UIButton *getInfoButton;

@property (weak, nonatomic) IBOutlet UITextView *appInfoTextView;
@property (weak, nonatomic) IBOutlet UITextView *resultInfoTextView;
@property (weak, nonatomic) IBOutlet UIButton *getResultButton;

@property (weak, nonatomic) IBOutlet UILabel *buildCreatedLabel;
@property (weak, nonatomic) IBOutlet UILabel *buildUpdatedLabel;

@property (nonatomic, strong) NSString *buildKey;
@property (nonatomic, strong) NSString *buildPassword;

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.aooIconIMV.layer.cornerRadius = 4;
    self.aooIconIMV.layer.masksToBounds = YES;
    NSString *iconUrl = HOST_URL_app_icons(self.appModel.buildIcon);
    [self.aooIconIMV sd_setImageWithURL:[NSURL URLWithString:iconUrl] placeholderImage:[UIImage imageNamed:@"app_icon"]];
    self.appNameLabel.text = self.appModel.buildName;
    self.appkeyTF.text = self.appModel.appKey;

    [self setBorder:self.installButton];
    [self setBorder:self.clearInfoButton];
    [self setBorder:self.getInfoButton];
    [self setBorder:self.appInfoTextView];
    [self setBorder:self.resultInfoTextView];
    [self setBorder:self.getResultButton];
}

- (IBAction)toViewNet:(UIBarButtonItem *)sender {

    if (self.appModel.buildKey.length == 0) {
        [MBProgressHUD showInfoOnView:self.view WithStatus:@"请先获取app信息" afterDelay:1];
        return;
    }

    NSString *urlString = [NSString stringWithFormat:@"https://www.pgyer.com/%@", self.appModel.buildKey];
    NSString *buildPassword = self.appModel.buildPassword;

    [PPTools jumpToDownloadPage:urlString buildPassword:buildPassword];
}

- (IBAction)toViewMoreVersions:(id)sender {

    if (self.appModel.buildKey.length == 0) {
        [MBProgressHUD showInfoOnView:self.view WithStatus:@"请先获取app信息" afterDelay:1];
        return;
    }

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //故事板界面跳转
    //从Storyboard中通过一个标识取出一个场景,返回的是场景绑定的VC实例
    // 根据id 获取一个界面 从故事板
    MoreVersionsVC *moreVC = [storyboard instantiateViewControllerWithIdentifier:@"story_moreVersionsVC"];
    moreVC.appModel = self.appModel;
    [self.navigationController pushViewController:moreVC animated:YES];
}

- (void)setBorder:(UIView *)view {
    view.layer.cornerRadius = 4;
    view.layer.borderColor = UIColor.lightGrayColor.CGColor;
    view.layer.borderWidth = 1;
}

- (IBAction)toInstallDirectly:(id)sender {
    [PPTools jumpToInstallDirectly:self.appModel.buildKey buildPassword:self.appModel.buildPassword];
}

- (IBAction)clearAllInfo:(id)sender {
    self.appInfoTextView.text = @"";
    self.resultInfoTextView.text = @"";
    self.buildCreatedLabel.text = @"";
    self.buildUpdatedLabel.text = @"";
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = @"";
}

- (IBAction)getAppInfo:(UIButton *)sender {

    NSString *params = [NSString stringWithFormat:@"_api_key=%@&appKey=%@", [RequestTool get_api_key], self.appkeyTF.text];

    WEAKSELF
    [RequestTool postWith:HOST_URL_app_view paramsString:params completeHandler:^(NSString * _Nullable responseString, NSDictionary * _Nullable responseDataDic, BOOL isSuccess, NSString * _Nullable message) {
        if (!isSuccess) {
            [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:message afterDelay:1.5];
            return;
        }

        weakSelf.appInfoTextView.text = [weakSelf formatResponseDataDic:responseDataDic];

        // iOS下载地址：https://www.pgyer.com/ykjiostest, 密码：qwer1234，版本：3.9.0, build: 52, 大小：47.2MB， 环境：130
        NSString *buildName = responseDataDic[@"buildName"];
        NSString *buildKey = responseDataDic[@"buildKey"];
        weakSelf.buildKey = buildKey;
        NSString *urlString = [NSString stringWithFormat:@"https://www.pgyer.com/%@", buildKey];
        // [NSString stringWithFormat:@"https://www.pgyer.com/%@", dic[@"buildShortcutUrl"]];
        NSString *buildPassword = responseDataDic[@"buildPassword"];
        weakSelf.buildPassword = buildPassword;
        NSString *versionString = responseDataDic[@"buildVersion"];
        NSString *buildString = responseDataDic[@"buildBuildVersion"];
        NSString *sizeString = [PPTools fileSizeFormat:[responseDataDic[@"buildFileSize"] longLongValue]];
        NSMutableString *resultString = [NSMutableString stringWithFormat:@"[%@] iOS端下载地址：%@", buildName, urlString];
        if (buildPassword.length > 0) {
            [resultString appendFormat:@", 密码：%@", buildPassword];
        }
        [resultString appendFormat:@", 版本：%@, build: %@, 大小：%@", versionString, buildString, sizeString];
        //        weakSelf.resultInfoTextView.text = resultString.copy;
        [weakSelf refreshResultTextView:resultString.copy imageUrl:responseDataDic[@"buildQRCodeURL"]];

        NSString *buildCreated = responseDataDic[@"buildCreated"];
        weakSelf.buildCreatedLabel.text = [NSString stringWithFormat:@"构建时间: %@", buildCreated];
        NSString *buildUpdated = responseDataDic[@"buildUpdated"];
        weakSelf.buildUpdatedLabel.text = [NSString stringWithFormat:@"更新时间: %@", buildUpdated];

        [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:@"请求成功" afterDelay:1.5];
    }];
}

- (void)refreshResultTextView:(NSString *)result imageUrl:(nullable NSString *)imageUrl {

    // 富文本 文字 + 图片
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage generateQRCodeFromString:imageUrl size:200];
    attachment.bounds = CGRectMake(0, 0, 200, 200);
    NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attachment];
    [attributedString appendAttributedString:imageString];

    NSAttributedString *textString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"\n%@", result] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]}];
    [attributedString appendAttributedString:textString];
    self.resultInfoTextView.attributedText = attributedString;
    self.resultInfoTextView.textAlignment = NSTextAlignmentLeft;
}

- (NSString *)formatResponseDataDic:(NSDictionary *)responseDataDic {
    NSError *error = nil;
    NSData *result = [NSJSONSerialization dataWithJSONObject:responseDataDic options:NSJSONWritingPrettyPrinted | NSJSONWritingWithoutEscapingSlashes error:&error];
    return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
}

#warning 图片和文字一起复制的时候, 部分app无法识别, 但是微信可以, Mac端
- (IBAction)copyInfo:(UIButton *)sender {

    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];

    NSMutableArray *array = [NSMutableArray array];

    if (self.buildKey.length > 0) {
        NSString *urlString = [NSString stringWithFormat:@"https://www.pgyer.com/%@", self.buildKey];
        UIImage *image = [UIImage generateQRCodeFromString:urlString size:500];
        NSData *data = UIImagePNGRepresentation(image);
        NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"qrcode.png"];
        [data writeToFile:filePath atomically:YES];
        //        pasteboard.image = image;

        NSMutableDictionary *items = [NSMutableDictionary dictionary];
#if TARGET_OS_MACCATALYST

        items[(NSString *)kUTTypePNG] = UIImagePNGRepresentation(image);
        items[(NSString *)kUTTypeTIFF] = UIImagePNGRepresentation(image);

#else
        items[(NSString *)kUTTypeImage] = image;
#endif

        [array addObject:items];
    }
    //    pasteboard.string = self.resultInfoTextView.text;

    NSMutableDictionary *items = [NSMutableDictionary dictionary];
#if TARGET_OS_MACCATALYST


    items[(NSString *)kUTTypeUTF8PlainText] = self.resultInfoTextView.text;
    items[(NSString *)kUTTypePlainText] = self.resultInfoTextView.text;

#else
    items[(NSString *)kUTTypePlainText] = self.resultInfoTextView.text;
#endif
    [array addObject:items];
    // 设置 items（数组）
    pasteboard.items = array;

    [MBProgressHUD showInfoOnView:self.view WithStatus:@"复制成功" afterDelay:1.5];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
